package com.kongjian.manage.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kongjian.manage.mapper.StRiverRMapper;
import com.kongjian.manage.mapper.StorageCapacityRelationMapper;
import com.kongjian.manage.mapper.WaterLevelRecordsMapper;
import com.kongjian.manage.model.entity.StRiverREntity;
import com.kongjian.manage.model.entity.StorageCapacityRelationEntity;
import com.kongjian.manage.model.entity.WaterLevelRecordsEntity;
import com.kongjian.manage.model.query.StorageCapacityQuery;
import com.kongjian.manage.model.vo.StorageCapacityVO;
import com.kongjian.manage.service.IStorageCapacityService;
import com.kongjian.manage.utils.CalcUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

import static com.kongjian.manage.utils.ExcelUtil.downLoadExcel;

/**
 * @author tangjunfeng
 * @Classname DeptServiceImpl.java
 * @Description 部门service
 * @Date 2023-10-10
 * @Version V1.0
 */
@Service
public class StorageCapacityServiceImpl implements IStorageCapacityService {


    @Autowired
    private StRiverRMapper stRiverRMapper;

    @Autowired
    private StorageCapacityRelationMapper storageCapacityRelationMapper;

    @Autowired
    private WaterLevelRecordsMapper waterLevelRecordsMapper;

    @Override
    public List<StorageCapacityVO> query() {
        //添加排序条件
        Date today = new Date(86400000L * (int) (System.currentTimeMillis() / 86400000.0) - 1000 * 60 * 60 * 8);
        Date yesterday = new Date(today.getTime() - (1000 * 60 * 60 * 25));
        StorageCapacityQuery storageCapacityQuery = new StorageCapacityQuery();
        storageCapacityQuery.setStartTime(yesterday);
        storageCapacityQuery.setEndTime(today);
        List<StorageCapacityVO> resultList = query(storageCapacityQuery);
        return resultList;
    }


    @Override
    public List<StorageCapacityVO> query(StorageCapacityQuery storageCapacityQuery) {
        //通过条件(时间)查询水位数据
        LambdaQueryWrapper<StRiverREntity> lambda = new LambdaQueryWrapper<>();
        lambda.between(StRiverREntity::getTm, storageCapacityQuery.getStartTime(), storageCapacityQuery.getEndTime());
        lambda.orderByAsc(StRiverREntity::getTm);
        List<StRiverREntity> stRiverREntities = stRiverRMapper.selectList(lambda);
        //返回前端的结果集
        List<StorageCapacityVO> resultList = new ArrayList<>();

        for (StRiverREntity stRiverREntity : stRiverREntities) {
            //查询大于水位的值
            LambdaQueryWrapper<StorageCapacityRelationEntity> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.gt(StorageCapacityRelationEntity::getRefer, stRiverREntity.getZ());
            lambdaQueryWrapper1.orderByAsc(StorageCapacityRelationEntity::getRefer);
            lambdaQueryWrapper1.last("limit 1");
            StorageCapacityRelationEntity max = storageCapacityRelationMapper.selectOne(lambdaQueryWrapper1);
            //查询小于水位的值
            LambdaQueryWrapper<StorageCapacityRelationEntity> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper2.lt(StorageCapacityRelationEntity::getRefer, stRiverREntity.getZ());
            lambdaQueryWrapper2.orderByDesc(StorageCapacityRelationEntity::getRefer);
            lambdaQueryWrapper2.last("limit 1");
            StorageCapacityRelationEntity min = storageCapacityRelationMapper.selectOne(lambdaQueryWrapper2);

            //以相邻两个水位、库容数据通过线性关系计算第三点的库容值
            BigDecimal formula = CalcUtil.formula(max.getRefer(), max.getValue(), min.getRefer(), min.getValue(), stRiverREntity.getZ());
            stRiverREntity.setQ(formula);
            StorageCapacityVO vo = new StorageCapacityVO();
            BeanUtils.copyProperties(stRiverREntity, vo);
            //查询报错过的记录
            LambdaQueryWrapper<WaterLevelRecordsEntity> waterLambda = new LambdaQueryWrapper<>();
            waterLambda.eq(WaterLevelRecordsEntity::getRecordTime, stRiverREntity.getTm());
            WaterLevelRecordsEntity waterLevelRecordsEntity = waterLevelRecordsMapper.selectOne(waterLambda);
            if (waterLevelRecordsEntity != null) {
                vo.setWarehousing(waterLevelRecordsEntity.getWarehousing());
                vo.setPower(waterLevelRecordsEntity.getPower());
                vo.setWater(waterLevelRecordsEntity.getWater());
                vo.setEcologyFlow(waterLevelRecordsEntity.getEcologyflow());
                vo.setDownFlow(waterLevelRecordsEntity.getDownflow());
            }

            resultList.add(vo);
        }

        return resultList;
    }

    @Override
    public void export(List<StorageCapacityVO> result, HttpServletResponse response) throws IOException {
        TemplateExportParams params = new TemplateExportParams(
                "doc/example.xlsx");
        Map<String, Object> map = new HashMap<>();

        List<Map<String, String>> listMap = new ArrayList<>();
        String yyyymm = "";
        String dd = "";
        for (int i = 0; i < result.size(); i++) {
            Map<String, String> lm = new HashMap<>();
            StorageCapacityVO vo = result.get(i);
            Date tm = vo.getTm();
            dd = DateUtil.format(tm, "dd");
            String time = DateUtil.format(tm, "HH:mm:ss");
            yyyymm = DateUtil.format(tm, "yyyy 年 MM 月");

            lm.put("time", time == null ? "" : time);
            lm.put("water", vo.getWater() == null ? "" : vo.getWater() + "");
            lm.put("power", vo.getPower() == null ? "" : vo.getPower() + "");
            lm.put("ecologyFlow", vo.getEcologyFlow() == null ? "" : vo.getEcologyFlow() + "");
            lm.put("downFlow", vo.getDownFlow() == null ? "" : vo.getDownFlow() + "");
            lm.put("warehousing", vo.getWarehousing() == null ? "" : vo.getWarehousing() + "");
            lm.put("q", vo.getQ() == null ? "" : vo.getQ() + "");
            lm.put("z", vo.getZ() == null ? "" : vo.getZ() + "");
            listMap.add(lm);
        }
        map.put("maplist", listMap);

        map.put("yyyymm", yyyymm);
        map.put("dd", dd);

        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
       /* File savefile = new File("D:/excel/");
        if (!savefile.exists()) {
            savefile.mkdirs();
        }
        FileOutputStream fos = new FileOutputStream("D:/excel/水位记录表_map.xls");
        workbook.write(fos);
        fos.close();*/
        String fileName = "file_" + dd + ".xlsx";
        downLoadExcel(fileName, response, workbook);
    }


}
